<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--商品分类-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="className"
            placeholder="请输入分类名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="goodsClassList"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--商品数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="商品名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入商品名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="商品状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择商品状态" clearable size="small">
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['goods:goods:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="ids.length<1"
              @click="handleBatchStatusChange('0')"
              v-hasPermi="['goods:goods:edit']"
            >批量上架</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="ids.length<1"
              @click="handleBatchStatusChange('1')"
              v-hasPermi="['goods:goods:edit']"
            >批量下架</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="商品信息" align="center" width="370" >
            <template slot-scope="scope">

              <div style="height: 100%">
                <div style="display: inline-block;float:left;width: 80px;height: 80px"  >
                  <el-image :src="baseUrl+scope.row.picturePath"></el-image>
                </div>
                <div style="display: inline-block;float:left;margin-left: 15px;height: 100%;width: 250px">
                  <div style="text-align: left">{{scope.row.goodsCode}}</div>
                  <div style="text-align: left">{{scope.row.name}}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="售价" align="center" prop="referencePrice">
            <template slot-scope="scope">
             {{scope.row.referencePrice}} <br>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdatePrice(scope.row)"
                v-hasPermi="['goods:goods:edit']"
              >修改价格</el-button>
            </template>
          </el-table-column>
          <el-table-column label="库存" align="center" prop="stock" >
            <template slot-scope="scope">
              {{scope.row.stock}} <br>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdateStock(scope.row)"
                v-hasPermi="['goods:goods:edit']"
              >修改库存</el-button>
            </template>
          </el-table-column>
          <el-table-column label="上架" align="center" prop="status">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
<!--          <el-table-column label="快递费模板" align="center" prop="templateId" />-->
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['goods:goods:edit']"
              >编辑商品</el-button>
              <br>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdateContent(scope.row)"
                v-hasPermi="['goods:goods:edit']"
              >编辑描述</el-button>
<!--              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['goods:goods:remove']"
              >删除</el-button>-->
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改商品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品编码" prop="goodsCode">
              <el-input v-model="form.goodsCode" placeholder="请输入商品编码" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品属性"  v-if="form.attributeValueList &&form.attributeValueList.length > 0" >
              <div style="border: 1px solid #c0ccda">
                <el-row >
                  <div v-for="(item,index) in form.attributeValueList">
                    <el-col v-if="item.type == '0'" :span="12"  style="margin: 10px 0" >
                      <el-form-item :label="item.attributeName" >
                          <el-select v-model="form.attributeValueList[index].attributeValue" :placeholder="'请选择'+item.attributeName">
                            <el-option
                              v-for="option in goodsAttributeList[index].optionList"
                              :key="option.optionName"
                              :label="option.optionName"
                              :value="option.optionName"
                            />
                          </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col v-if="item.type == '1'" :span="12"  style="margin: 10px 0" >
                      <el-form-item :label="item.attributeName" >
                        <el-input  v-model="form.attributeValueList[index].attributeValue" style="width: 78.5%" :placeholder="'请输入'+item.attributeName" />
                      </el-form-item>
                    </el-col>
                    <el-col v-if="item.type == '2'" :span="12"  style="margin: 10px 0" >
                      <el-form-item :label="item.attributeName" >
                        <el-date-picker
                          v-model="form.attributeValueList[index].attributeValue"
                          type="date"
                          :placeholder="'选择'+item.attributeName">
                        </el-date-picker>
                      </el-form-item>
                    </el-col>
                    <el-col v-if="item.type == '3'" :span="12"  style="margin: 10px 0" >
                      <el-form-item :label="item.attributeName" >
                        <el-time-picker
                          v-model="form.attributeValueList[index].attributeValue"
                          :placeholder="'选择'+item.attributeName">
                        </el-time-picker>
                      </el-form-item>
                    </el-col>
                    <el-col v-if="item.type == '4'" :span="24"  style="margin: 10px 0" >
                      <el-form-item :label="item.attributeName" >
                        <el-date-picker
                          v-model="form.attributeValueList[index].attributeValue"
                          type="daterange"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期">
                        </el-date-picker>
                      </el-form-item>
                    </el-col>
                    <el-col v-if="item.type == '5'" :span="24"  style="margin: 10px 0" >
                      <el-form-item :label="item.attributeName" >
                        <el-time-picker
                          v-model="form.attributeValueList[index].attributeValue"
                          is-range
                          range-separator="至"
                          start-placeholder="开始时间"
                          end-placeholder="结束时间"
                          placeholder="选择时间范围">
                        </el-time-picker>
                      </el-form-item>
                    </el-col>
                    <el-col v-if="item.type == '6'" :span="11"  style="margin: 10px 0" >
                      <el-form-item :label="item.attributeName" prop="">
                        <el-switch
                          v-model="form.attributeValueList[index].attributeValue"
                          active-value="0"
                          inactive-value="1"
                        >
                        </el-switch>
                      </el-form-item>
                    </el-col>
                  </div>
                </el-row>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品视频" prop="video">
              <div class="picture"  >
                <video v-if="form.video" style="width:100%;" :src="baseUrl+form.videoPath" :autoplay="false" controls @click="handleVideoSelector"></video>
                <i v-else style="font-size: 16px" class="el-icon-plus" @click="handleVideoSelector"></i>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品图片" prop="picFileList" >
              <div class="picture" v-for="(item,index) in form.picFileList" style="position: relative" >
                <div  style="position: absolute;right: 0px;top: 0px;width: 20px;height: 20px;line-height:20px;background: #D9F3FE;color:#1890FF;text-align: center;z-index: 9;" @click="removePicture(index)" >
                  x
                </div>
                <el-image   style="width:100%;" :src="baseUrl+item.filePath"></el-image>
              </div>
              <div class="picture" v-if="form.picFileList.length < 10" @click="handleSelector" >
                <i  style="font-size: 16px" class="el-icon-plus" @click="handleSelector"></i>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品价格" prop="referencePrice">
              <el-input v-model="form.referencePrice" placeholder="请输入商品价格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品分类" prop="goodsClassId">
              <treeselect @input="checkClassId" v-model="form.goodsClassId" :options="goodsClassList" :normalizer="normalizer" :show-count="true" placeholder="请选择商品分类" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品规格" >
              <el-checkbox-group v-model="form.unitsKeys" @change="handleUnitKeyChange" >
                <el-checkbox v-for="key in unitsKeyList" :label="key.unitName"></el-checkbox>
              </el-checkbox-group>
              <div v-for="unitKey in unitsKeyList" v-if="form.unitsKeys && form.unitsKeys.indexOf(unitKey.unitName) > -1">
                <span>{{unitKey.unitName}}</span>
                <el-checkbox-group v-if="form.unitsValues[form.unitsKeys.indexOf(unitKey.unitName)]" v-model="form.unitsValues[form.unitsKeys.indexOf(unitKey.unitName)].unitValue" @change="handleUnitValueChange" >
                  <el-checkbox v-for="value in unitKey.unitsValueList"  :label="value.unitValue"></el-checkbox>
                </el-checkbox-group>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="价格及库存" prop="">
              <el-row v-if="form.unitsList && form.unitsList[0] && form.unitsList[0].goodsUnit" style="margin-bottom: 10px">
                <el-col :span="5" style="margin-right: 10px">
                  <treeselect  v-model="setting.unitsSelected" :options="setting.unitsOptions" :multiple="true"  :show-count="true" placeholder="请选择规格" />
                </el-col>

                <el-col :span="4" style="margin-right: 10px">
                  <el-input v-model="setting.stock" placeholder="库存" />
                </el-col>
                <el-col :span="4" style="margin-right: 10px">
                  <el-input v-model="setting.price" placeholder="售价" />
                </el-col>
                <el-col :span="4" style="margin-right: 10px">
                  <el-input v-model="setting.groupPrice" placeholder="拼购价" />
                </el-col>
                <el-col :span="4" style="margin-right: 10px">
                  <el-input v-model="setting.panicPrice" placeholder="活动价" />
                </el-col>
                <el-col :span="4" style="margin-right: 10px">
                  <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="batchSetting"
                  >批量设置</el-button>
                </el-col>
              </el-row>

              <el-row>
                <el-table :data="form.unitsList" border  style="width: 100%">
                  <el-table-column v-if="form.unitsList && form.unitsList[0] && form.unitsList[0].goodsUnit"   prop="goodsUnit" label="规格" width="">
                    <template slot-scope="scope">
                      {{unitFormat(scope.row.goodsUnit)}}
                    </template>
                  </el-table-column>
                  <el-table-column  prop="stock" label="库存" >
                    <template slot-scope="scope">
                      <el-form-item label-width="0"  :prop="'unitsList.' + scope.$index + '.stock'"  :rules="{ required: true,pattern:/^[+]{0,1}(\d+)$/,message: '商品库存必须为正整数', trigger: 'blur' }" >
                        <el-input v-model="scope.row.stock"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column  prop="price" label="售价">
                    <template slot-scope="scope">
                      <el-form-item label-width="0"  :prop="'unitsList.' + scope.$index + '.price'" :rules='{ required: true,pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,message: "请输入正确金额,必须是数字型,且小数位最多保留两位！",trigger: "blur" }' >
                        <el-input v-model="scope.row.price"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column  prop="groupPrice" label="拼购价">
                    <template slot-scope="scope">
                      <el-form-item label-width="0"  :prop="'unitsList.' + scope.$index + '.groupPrice'" :rules='{ required: true,pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,message: "请输入正确金额,必须是数字型,且小数位最多保留两位！",trigger: "blur" }' >
                        <el-input v-model="scope.row.groupPrice"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column  prop="panicPrice" label="活动价">
                    <template slot-scope="scope">
                      <el-form-item label-width="0"  :prop="'unitsList.' + scope.$index + '.panicPrice'" :rules='{ required: true,pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,message: "请输入正确金额,必须是数字型,且小数位最多保留两位！",trigger: "blur" }' >
                        <el-input v-model="scope.row.panicPrice"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column  prop="skuCode" label="sku编码">
                    <template slot-scope="scope">
                      <el-form-item label-width="0"  :prop="'unitsList.' + scope.$index + '.skuCode'" :rules='{ required: true,message: "SKU码不能为空",trigger: "blur" }' >
                        <el-input v-model="scope.row.skuCode"/>
                      </el-form-item>
<!--                      <el-input v-model="scope.row.skuCode"/>-->
                    </template>
                  </el-table-column>
                </el-table>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品详情" prop="content">
              <detail-editor v-model="form.content" :min-height="250"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="快递费模板" prop="templateId">
              <el-select v-model="form.templateId" placeholder="请选择运费模板">
                <el-option
                  v-for="item in templateList"
                  :key="item.id"
                  :label="item.templateName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 视频选择器 -->
    <picture-selector
      ref="videoSelector"
      :open="videoSelector"
      :multiple="1"
      @input="getCheckedVideo"
      @close="closeSelector"
    ></picture-selector>

    <!-- 图片选择器 -->
    <picture-selector
      ref="selector"
      :open="selector"
      :multiple="10-form.picFileList.length"
      @input="getCheckedPicture"
      @close="closeSelector"
    ></picture-selector>

    <!--    编辑价格弹窗-->
    <el-dialog :title="title" :visible.sync="price" width="800px" append-to-body>
      <el-form ref="editForm" :model="editForm" :rules="rules"  label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品名称" >
              <b>{{editForm.name}}</b>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="市场参考价" prop="referencePrice"  :rules='{ required: true,pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,message: "请输入正确金额,必须是数字型,且小数位最多保留两位！",trigger: "blur" }'>
              <el-input  v-model="editForm.referencePrice" placeholder="请输入市场参考价" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-table :data="editForm.unitsList" border  style="width: 100%">
              <el-table-column v-if="editForm.unitsList && editForm.unitsList[0] && editForm.unitsList[0].goodsUnit"   prop="goodsUnit" label="规格" width="">
                <template slot-scope="scope">
                  {{unitFormat(scope.row.goodsUnit)}}
                </template>
              </el-table-column>
              <el-table-column  prop="price" label="售价"  >
                <template slot-scope="scope" >
                  <el-form-item label-width="0" style="margin-bottom: 0" :prop="'unitsList.' + scope.$index + '.price'" :rules='{ required: true,pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,message: "请输入正确金额,必须是数字型,且小数位最多保留两位！",trigger: "blur" }'>
                    <el-input v-model="scope.row.price"/>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column  prop="groupPrice" label="拼购价">
                <template slot-scope="scope">
                  <el-form-item label-width="0" style="margin-bottom: 0" :prop="'unitsList.' + scope.$index + '.groupPrice'" :rules='{ required: true,pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,message: "请输入正确金额,必须是数字型,且小数位最多保留两位！",trigger: "blur" }'>
                    <el-input v-model="scope.row.groupPrice"/>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column  prop="panicPrice" label="活动价">
                <template slot-scope="scope">
                  <el-form-item label-width="0" style="margin-bottom: 0" :prop="'unitsList.' + scope.$index + '.panicPrice'" :rules='{ required: true,pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,message: "请输入正确金额,必须是数字型,且小数位最多保留两位！",trigger: "blur" }'>
                    <el-input v-model="scope.row.panicPrice"/>
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPriceStockForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--    编辑库存弹窗-->
    <el-dialog :title="title" :visible.sync="stock" width="800px" append-to-body>
      <el-form ref="editForm"  :model="editForm" :rules="rules"  label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品名称" >
              <b>{{editForm.name}}</b>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-table :data="editForm.unitsList" border  style="width: 100%">
              <el-table-column v-if="editForm.unitsList && editForm.unitsList[0] && editForm.unitsList[0].goodsUnit"   prop="goodsUnit" label="规格" width="">
                <template slot-scope="scope">
                  {{unitFormat(scope.row.goodsUnit)}}
                </template>
              </el-table-column>
              <el-table-column  prop="stock" label="库存">
                <template slot-scope="scope">
                  <el-form-item label-width="0" style="margin-bottom: 0" :prop="'unitsList.' + scope.$index + '.stock'"  :rules="{ required: true,pattern:/^[+]{0,1}(\d+)$/,message: '商品库存必须为正整数', trigger: 'blur' }">
                    <el-input v-model="scope.row.stock"/>
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPriceStockForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--    编辑描述弹窗-->
    <el-dialog :title="title" :visible.sync="contentEdit" width="800px" append-to-body>
      <el-form ref="editForm"  :model="editForm" :rules="rules"  label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品名称" >
              <b>{{editForm.name}}</b>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品详情">
              <detail-editor v-model="editForm.content" :min-height="500"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPriceStockForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listGoods,
  getGoods,
  delGoods,
  addGoods,
  updateGoods,
  changeGoodsStatus,
  batchChangeGoodsStatus, updateGoodsPriceStock
} from "@/api/goods/goods";
import PictureSelector from "@/views/picture/file/selector";
import {listGoodsClass} from "@/api/goods/goodsClass";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {attributeList} from "@/api/goods/attribute";
import {parseTime} from "@/utils/pzb";
import {templateList} from "@/api/goods/template";
import {unitsKeyValueList} from "@/api/goods/unitsKey";

export default {
  name: "Goods",
  components: {
    PictureSelector,
    Treeselect
  },
  watch: {
    // 根据名称筛选分类树
    className(val) {
      this.$refs.tree.filter(val);
    }
  },
  data() {
    return {
      className:"",
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      selector: false,
      videoSelector:false,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      baseUrl:process.env.VUE_APP_BASE_API,
      // 总条数
      total: 0,
      // 商品管理表格数据
      goodsList: [],
      defaultProps: {
        children: "children",
        label: "className"
      },
      goodsClassList:[],
      unitsKeyList:[],
      goodsUnitsList:[],
      goodsAttributeList:[],
      // 运费模板数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //价格弹出层
      price: false,
      //库存弹出层
      stock: false,
      //详情弹出层
      contentEdit: false,
      // 商品状态：0为下架，1为上架字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        goodsClassId: null,
        status: null
      },
      // 表单参数
      form: {
        picFileList:[]
      },
      editForm:{},
      setting:{
        unitsOptions:[],
        unitsSelected:[],
        stock: null,
        price: null,
        groupPrice:null,
      },
      // 表单校验
      rules: {
        goodsCode: [
          { required: true, message: "商品编码不能为空", trigger: "blur" },
          { max: 20, message: '商品编码长度不能超过20个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: "商品名称不能为空", trigger: "blur" },
          { max: 50, message: '商品名称长度不能超过20个字符', trigger: 'blur' }
        ],
        picFileList: [
          { required: true, message: "商品图片不能为空", trigger: "blur" }
        ],
        referencePrice: [
          { required: true, pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,message: "商品价格只能为数字", trigger: "blur" }
        ],
        goodsClassId: [
          { required: true, message: "商品分类不能为空", trigger: ["blur","change"] }
        ],
        templateId: [
          { required: true, message: "运费模板不能为空", trigger: ["blur","change"] }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getGoodsClassList();
    this.getUnitsKeyList();
    this.getGoodsAttributeList();
    this.getTemplateList();
    this.getDicts("goods_status").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询商品管理列表 */
    getList() {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },//商品分类
    getGoodsClassList() {
      listGoodsClass({status:0}).then(response => {
        this.goodsClassList = this.handleTree(response.data, "id");
      });
    },//商品规格
    getUnitsKeyList(){
      unitsKeyValueList().then(res =>{
        this.unitsKeyList = res.data;
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.className.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.goodsClassId = data.id;
      this.getList();
    },
    //商品属性
    getGoodsAttributeList(){
      attributeList({status:'0'}).then(response => {
        this.goodsAttributeList = response.data;
      });
    },
    getTemplateList() {
      templateList({}).then(response => {
        this.templateList = response.data;
      });
    },
    normalizer(node) {
      return {
        id: node.id,
        label: node.className
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.price = false;
      this.stock = false;
      this.contentEdit = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        extAppid: null,
        goodsCode: null,
        name: null,
        video: null,
        videoPath:null,
        picFileList: [],
        goodsClassId: null,
        referencePrice: null,
        unitsList:[],
        //选中的规格
        unitsKeys:[],
        unitsValues:[],
        status: "1",
        content: null,
        attributeValueList:[],
        templateId: null
      };
      this.editForm = {
        id: null,
        extAppid: null,
        goodsCode: null,
        name: null,
        video: null,
        videoPath:null,
        picFileList: [],
        goodsClassId: null,
        referencePrice: null,
        unitsList:[],
        //选中的规格
        unitsKeys:[],
        unitsValues:[],
        status: "1",
        content: null,
        attributeValueList:[],
        templateId: null
      };
      this.setting = {
          unitsOptions:[],
          unitsSelected:[],
          stock: null,
          price: null,
          groupPrice:null,
          panicPrice:null
      },
      this.goodsUnitsList = [];
      this.resetForm("form");
      this.resetForm("editForm")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.goodsClassId = null
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      const unit = {
        id: null,
        extAppid: null,
        goodsId: null,
        goodsUnit:null,
        skuCode: null,
        price: null,
        groupPrice: null,
        panicPrice :null,
        stock: null
      };
      this.form.unitsList.push(unit);
      attributeList({status:'0'}).then(response => {
        this.open = true;
        this.title = "添加商品管理";
        this.goodsAttributeList = response.data;
        if(response.data){
          let attributeValueList=[];
          for (let i = 0; i < response.data.length; i++) {
            const value=  {
              type: response.data[i].type,
              attributeId: response.data[i].id,
              attributeName: response.data[i].attributeName,
              attributeValue: response.data[i].defaultValue,
            };
            attributeValueList.push(value)
          }
          this.form.attributeValueList=attributeValueList;
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getGoods(id).then(response => {
        this.form = response.data;
        //组织unitsKeys
        this.form.unitsKeys=[];
        try {
          this.form.unitsList.forEach(units =>{
            if (units.goodsUnit) {
              const unit = JSON.parse(units.goodsUnit);
              this.form.unitsKeys=Object.keys(unit);
              throw Error();
            }
          })
        } catch (e) {
        }
        //组织unitsValues
        this.form.unitsValues=[];
        if (this.form.unitsKeys) {
          this.form.unitsKeys.forEach(key =>{
            this.form.unitsValues.push({unitName:key,unitValue:[]});
          })
        }
        this.form.unitsValues.forEach(values =>{
          for (let i = 0; i < this.form.unitsList.length; i++) {
            if (this.form.unitsList[i].goodsUnit) {
              const unit = JSON.parse(this.form.unitsList[i].goodsUnit);
              if(values.unitValue.indexOf(unit[values.unitName])<0){
                values.unitValue.push(unit[values.unitName])
              }
            }
          }
        })
        let attributeValueList=[];
        for (let i = 0; i < this.goodsAttributeList.length; i++) {
          let value=  {
            type: this.goodsAttributeList[i].type,
            attributeId: this.goodsAttributeList[i].id,
            attributeName: this.goodsAttributeList[i].attributeName,
            attributeValue: this.goodsAttributeList[i].defaultValue
          };
          for (let j = 0; j < this.form.attributeValueList.length; j++) {
            if(this.goodsAttributeList[i].id == this.form.attributeValueList[j].attributeId ){
              if(this.form.attributeValueList[j].attributeValue){
                if(this.form.attributeValueList[j].type == '3'){
                  let timeArray = this.form.attributeValueList[j].attributeValue.split(":");
                  value.attributeValue = new Date(2000,1,1,timeArray[0],timeArray[1],timeArray[2])
                }else if(this.form.attributeValueList[j].type == '4'){
                  value.attributeValue = this.form.attributeValueList[j].attributeValue.split("至")
                }else if(this.form.attributeValueList[j].type == '5'){
                  let timeArray = this.form.attributeValueList[j].attributeValue.split("至");
                  value.attributeValue=[]
                  let timeArray0 = timeArray[0].split(":");
                  value.attributeValue.push(new Date(2000,1,1,timeArray0[0],timeArray0[1],timeArray0[2]));
                  let timeArray1 = timeArray[1].split(":");
                  value.attributeValue.push(new Date(2000,1,1,timeArray1[0],timeArray1[1],timeArray1[2]));
                }else {
                  value.attributeValue = this.form.attributeValueList[j].attributeValue
                }
              }
              break;
            }
          }
          attributeValueList.push(value);
        }
        this.form.attributeValueList=attributeValueList;
        //初始化批量选择
        this.form.unitsList.forEach(unit=>{
          this.setting.unitsOptions.push({id:this.unitFormat(unit.goodsUnit),label: this.unitFormat(unit.goodsUnit)})
        })
        this.open = true;
        this.title = "修改商品管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          for (let i = 0; i < this.form.attributeValueList.length; i++) {
            if(this.form.attributeValueList[i].attributeValue){
              if(this.form.attributeValueList[i].type == '2' ){
                this.form.attributeValueList[i].attributeValue = parseTime(this.form.attributeValueList[i].attributeValue, '{y}-{m}-{d}')
              }else if(this.form.attributeValueList[i].type == '3'){
                this.form.attributeValueList[i].attributeValue = parseTime(this.form.attributeValueList[i].attributeValue, '{h}:{i}:{s}')
              }else if(this.form.attributeValueList[i].type == '4'){
                this.form.attributeValueList[i].attributeValue=parseTime(this.form.attributeValueList[i].attributeValue[0],'{y}-{m}-{d}')+"至"+parseTime(this.form.attributeValueList[i].attributeValue[1],'{y}-{m}-{d}')
              }else if(this.form.attributeValueList[i].type == '5'){
                this.form.attributeValueList[i].attributeValue=parseTime(this.form.attributeValueList[i].attributeValue[0],'{h}:{i}:{s}')+"至"+parseTime(this.form.attributeValueList[i].attributeValue[1],'{h}:{i}:{s}')
              }
            }
          }
          if (this.form.id != null) {
            updateGoods(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoods(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除商品管理编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delGoods(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 打开图片选择器 */
    handleSelector(){
      this.selector=true;
    },
    getCheckedPicture(checkedFileList){
      if(checkedFileList.length>0){
        for (let i = 0; i < checkedFileList.length; i++) {
          this.form.picFileList.push(checkedFileList[i])
        }
        console.log(this.form.picFileList)
        this.$refs.form.validateField('picFileList');
      }
    },
    /** 打开视频选择器 */
    handleVideoSelector(){
      this.videoSelector=true;
    },
    getCheckedVideo(checkedFileList){
      if(checkedFileList.length>0){
        this.form.video = checkedFileList[0].id;
        this.form.videoPath = checkedFileList[0].filePath;
      }
    },
    //关闭选择器
    closeSelector(){
      this.selector=false;
      this.videoSelector = false;
    },
    removePicture(index){
      this.form.picFileList.splice(index, 1);
    },
    handleUnitKeyChange(){
      this.unitsKeyList.forEach(unitsKey =>{
        if(this.form.unitsKeys.indexOf(unitsKey.unitName) > -1){
          if(this.form.unitsValues.findIndex(value => (value.unitName === unitsKey.unitName)) < 0){
            this.form.unitsValues.push({unitName:unitsKey.unitName,unitValue:[]})
          }
        }else {
          const index = this.form.unitsValues.findIndex(value => (value.unitName === unitsKey.unitName));
          if(index > -1){
            this.form.unitsValues.splice(index,1)
          }
        }
      })
      this.handleUnitValueChange();
    },
    handleUnitValueChange(){
      this.goodsUnitsList=[];
      let bl = true;
      for (let i = 0; i < this.form.unitsValues.length; i++) {
        if(bl){
          if(this.form.unitsValues[i] && this.form.unitsValues[i].unitValue.length>0 ) {
            this.form.unitsValues[i].unitValue.forEach(value => {
              let unit = {}
              unit[this.form.unitsValues[i].unitName] = value;
              this.goodsUnitsList.push(unit);
            })
            bl = false;
            continue;
          }
        }else {
          if(this.form.unitsValues[i].unitValue ){
            this.goodsUnitsList=this.forFn(this.goodsUnitsList,this.form.unitsValues[i])
          }
        }
      }
      this.form.unitsList=[];
      //组织批量选择规格选项
      this.setting.unitsOptions = [];
      this.goodsUnitsList.forEach(unit=>{
        let obj = {
          id: null,
          extAppid: null,
          goodsId: null,
          goodsUnit:JSON.stringify(unit),
          skuCode: null,
          price: null,
          groupPrice: null,
          panicPrice: null,
          stock: null
        };
        this.form.unitsList.push(obj)
        this.setting.unitsOptions.push({id:this.unitFormat(JSON.stringify(unit)),label: this.unitFormat(JSON.stringify(unit))})
      })
      this.setting.unitsSelected = [];
      if (this.form.unitsList.length == 0) {
        const unit = {
          id: null,
          extAppid: null,
          goodsId: null,
          goodsUnit:null,
          skuCode: null,
          price: null,
          groupPrice: null,
          panicPrice:null,
          stock: null
        };
        this.form.unitsList.push(unit);
      }
    },
    //递归
    forFn(unitList,item){
        let goodsUnitsList = [];
        if (item.unitValue && item.unitValue.length >0 ){
          unitList.forEach(unit=>{
            item.unitValue.forEach(value => {
              let obj=JSON.parse(JSON.stringify(unit));
              obj[item.unitName] = value;
              goodsUnitsList.push(obj)
            })
          })
        }else {
          return unitList
        }
        return goodsUnitsList;
    },
    unitFormat(obj){
      let str = ''
      if(obj){
        let a = Object.values(JSON.parse(obj));
        a.forEach(value => {
          str+=value+"/";
        })
      }
      return str;
    },
    //批量设置
    batchSetting(){
      this.form.unitsList.forEach(item =>{
        const index = this.setting.unitsSelected.findIndex(unit => unit == this.unitFormat(item.goodsUnit))
        if(index > -1){
          if(this.setting.price)
            item.price=this.setting.price
          if(this.setting.stock)
            item.stock=this.setting.stock
          if(this.setting.groupPrice)
            item.groupPrice=this.setting.groupPrice
          if(this.setting.panicPrice)
            item.panicPrice = this.setting.panicPrice
        }
      })
    },
    // 商品状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "上架" : "下架";
      this.$confirm('确认要"' + text + '""' + row.name + '"吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return changeGoodsStatus(row.id, row.status);
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    handleBatchStatusChange(status) {
      let text = status === "0" ? "上架" : "下架";
      this.$confirm('确认要"' + text + '"选中商品吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(()=> {
        return batchChangeGoodsStatus(this.ids, status);
      }).then(() => {
        this.msgSuccess(text + "成功");
        this.getList();
      }).catch(function() {
      });
    },
    handleUpdatePrice(row){
      this.reset();
      const id = row.id || this.ids
      getGoods(id).then(response => {
        this.editForm = response.data;
        this.price = true;
        this.title = "编辑商品价格";
      });
    },
    handleUpdateStock(row){
      this.reset();
      const id = row.id || this.ids
      getGoods(id).then(response => {
        this.editForm = response.data;
        this.stock = true;
        this.title = "编辑商品库存";
      });
    },
    submitPriceStockForm() {
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          updateGoodsPriceStock(this.editForm).then(response => {
            this.msgSuccess("修改成功");
            this.stock = false;
            this.price=false;
            this.contentEdit = false;
            this.getList();
          });
        }
      });
    },
    handleUpdateContent(row){
      this.reset();
      const id = row.id ;
      getGoods(id).then(response => {
        this.editForm = response.data;
        this.contentEdit = true;
        this.title = "编辑商品描述";
      });
    },
    //值变化重新校验
    checkClassId(){
      this.$nextTick(() => {
        this.$refs.form.validateField('goodsClassId');
      })
    }
  }
};
</script>
<style lang="scss" scoped>
.picture{
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 120px;
  height: 120px;
  cursor: pointer;
  line-height: 118px;
  vertical-align: top;
  text-align: center;
  float: left;
  margin-right: 10px;
  margin-bottom: 10px;
}
</style>
